package com.yanqu.road.server.manager.activity.bulletscreen;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.pb.activity.BulletScreenProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class CrossActivityBulletScreen {

    private ActivityInfo activityInfo;

    //弹幕-----------------
    private Object barrageLock = new Object();

    private AtomicLong contentId;

    private List<CrossActivityBarrageMessage> messageList;

    private int newNum = 0;

    //上次推送ID
    private long lastSyncContentId;


    public CrossActivityBulletScreen(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void init(){
        contentId = new AtomicLong(0);
        List<CrossActivityBarrageMessage> tempMessageList = new ArrayList<>();
        messageList = tempMessageList;
        newNum = 0;
        lastSyncContentId = 0;
    }

    /**
     * 弹幕
     * @param content
     * @param userId
     * @return
     */
    public CrossActivityBarrageMessage addBarrageMessage(String content, long userId, String nickName, long serverId){
        CrossActivityBarrageMessage msg = new CrossActivityBarrageMessage();
        msg.setActivityId(activityInfo.getActivityId());
        msg.setUserId(userId);
        msg.setServerId(serverId);
        msg.setContent(content);
        msg.setNickName(nickName);
        msg.setPostTime(System.currentTimeMillis());
        long size;
        synchronized (barrageLock){
            newNum++;
            msg.setContentId(contentId.incrementAndGet());
            messageList.add(msg);
            size = messageList.size();
        }
//        CrossActivityBulletScreenMgr.getLogger().info("activityId {} bullet message size {}", activityInfo.getActivityId(), size);
        return msg;
    }


    /**
     * 获取弹幕
     * @return
     */
    public List<CrossActivityBarrageMessage> getMessageList(){
        synchronized (barrageLock){
            return new ArrayList<>(messageList);
        }
    }

    /**
     * 同步弹幕给区服
     */
    public void syncBarrageMessageToServer(){
        if(activityInfo == null || DateHelper.getCurrentSecond() > activityInfo.getEndShowTime()){
            return;
        }
        int needSyncSize;
        synchronized (barrageLock){
            needSyncSize = newNum;
            newNum = 0;
            if(messageList.size() > 0) {
                lastSyncContentId = messageList.get(messageList.size() - 1).getContentId();
            }else {
                lastSyncContentId = 0;
            }
        }
        if(needSyncSize > 0 && lastSyncContentId > 0){
            List<CrossActivityBarrageMessage> allList = getMessageList();
            List<CrossActivityBarrageMessage> syncList = new ArrayList<>();
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
            int len = allList.size();
            for(int i = len -1; i >= 0 && needSyncSize > 0; i--){
                CrossActivityBarrageMessage msg = allList.get(i);
                if(msg.getContentId() <= lastSyncContentId){
                    syncList.add(msg);
                    needSyncSize--;
                }
                //不取过期数据
                if(msg.getPostTime() < zeroTime){
                    syncList.remove(msg);
                    break;
                }
            }
            if(syncList.size() > 0){
                Collections.reverse(syncList);
                  for(long serverId : activityInfo.getServerIdList()){
                      CrossActivityBulletScreenMgr.getLogger().info("push Barrage message to server {} : {} ", serverId, syncList.size());
                      BulletScreenProto.BulletScreenContentListRespMsg.Builder syncMsg = CrossActivityBulletScreenMgr.getMsgListBuilder2(syncList);
                      syncMsg.setActivityId(activityInfo.getActivityId());
                      MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.A_ACTIVITY_BARRAGE_MESSAGE_PUSH, syncMsg));
                  }
            }
        }
    }

    /**
     * 清理过期数据
     */
    public void removeOutTimeMsg(){
        if(activityInfo == null){
            return;
        }
        long zeroTimeStamp = LocalDateTimeHelper.getZeroTimeTimeStamp();
        synchronized (barrageLock){
            Iterator<CrossActivityBarrageMessage> iterator = messageList.iterator();
            while (iterator.hasNext()){
                CrossActivityBarrageMessage msg = iterator.next();
                if(msg.getPostTime() < zeroTimeStamp){
                    iterator.remove();
                }
            }
        }
    }

    /**
    * 描述：变更玩家弹幕
    * 作者：zrq
    * 时间：2022/8/5
    * 参数：
    玩家编号，变更内容
    * 返回值：操作码
    **/
    public int changePlayerMsg(long userId, long serverId, String content, long contentId){
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        synchronized (barrageLock){
            Iterator<CrossActivityBarrageMessage> iterator = messageList.iterator();
            while (iterator.hasNext()){
                CrossActivityBarrageMessage msg = iterator.next();
                if(msg.getUserId() == userId && msg.getServerId() == serverId && msg.getContentId() == contentId){
                    msg.setContent(content);
                }
            }
        }
        return 0;
    }

    /**
    * 描述：查询玩家弹幕
    * 作者：zrq
    * 时间：2022/8/23
    * 参数：

    * 返回值：
    **/
    public JSONArray queryPlayerMsg(long userId, long serverId){
        JSONArray dataArray = new JSONArray();
        if(null == activityInfo){
            return dataArray;
        }
        synchronized (barrageLock){
            Iterator<CrossActivityBarrageMessage> iterator = messageList.iterator();
            while (iterator.hasNext()){
                CrossActivityBarrageMessage msg = iterator.next();
                if(msg.getUserId() == userId && msg.getServerId() == serverId){
                    JSONObject msgObj = new JSONObject();
                    msgObj.put("contentId", msg.getContentId());
                    msgObj.put("content", msg.getContent());
                    dataArray.add(msgObj);
                }
            }
        }
        return dataArray;
    }
}
